package com.wu.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 武爸爸
 * @create 2020-09-29 18:01
 */
//自定义的   算法
public class MyThree extends AbstractLoadBalancerRule {
    //每个服务访问3次。换下一个服务


    private int serverIndex =0;//默认为0  如果等于
    private int count =0 ;  //默认为0 如果等于3 换下一个服务

    //    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {  //是否有负载均衡
            return null;
        } else {
            Server server = null;  //定义一个空的服务

            while(server == null) {
                if (Thread.interrupted()) {  //线程是否中断
                    return null;
                }

                List<Server> upList = lb.getReachableServers(); //获取所有的可用的服务
                List<Server> allList = lb.getAllServers();    //获取全部的服务
                int serverCount = allList.size();  //所有服务的个数
                if (serverCount == 0) {   //服务为0
                    return null;
                }
                //核心算法
                /*int index = this.chooseRandomInt(serverCount);
                server = (Server)upList.get(index);*/
                if (count<3&&serverIndex<upList.size()){
                    server = upList.get(serverIndex);
                    count++;
                }
                else {

                    if (serverIndex>upList.size()-1){
                        serverIndex = 0 ;
                    }
                    else {
                        count = 1 ;
                        server = upList.get(serverIndex);
                        serverIndex++;
                    }



                }





                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    //随机数的核心算法
    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
